package com.borqs.music.ui.online;

import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.borqs.music.R;
import com.borqs.music.executor.MusicExecutor;
import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskAdapter;
import com.borqs.music.model.SingerInfo;
import com.borqs.music.tasks.GetPersonalArtistAlbumTask;
import com.borqs.music.ui.adapter.OnlineSingerListAdapter;
import com.borqs.music.util.AccountUtils;
import com.borqs.music.util.MusicUtils;

public class PersonalArtistAlbumActivity extends OnlineBaseActivity {

    private static final int MSG_CREATE_LIST = 0;
    private static final int MSG_TASK_FAILED = 1;
    private static final int DIALOG_LOADING_SONGS = 10;

    private String mListType;
    private List<SingerInfo> mList;
    private ArrayAdapter<SingerInfo> mAdapter;

    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch(msg.what) {
                case MSG_CREATE_LIST:
                    Collections.sort(mList, new Comparator<SingerInfo>() {
                        public int compare(SingerInfo s, SingerInfo t) {
                            Collator myCollator = Collator.getInstance(java.util.Locale.CHINA);
                            if (myCollator.compare(s.name, t.name) < 0)
                                return -1;
                            else if (myCollator.compare(s.name, t.name) > 0)
                                return 1;
                            else
                                return 0;
                        }
                    });

                    mAdapter = new OnlineSingerListAdapter(
                            PersonalArtistAlbumActivity.this, mList, getListView());
                    setListAdapter(mAdapter);
                    removeDialog(DIALOG_LOADING_SONGS);
                    break;
                case MSG_TASK_FAILED:
                    removeDialog(DIALOG_LOADING_SONGS);
                    break;
                default:
                    break;
            }
        };
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.personal_media_list);
        MusicUtils.addNowPlayingListener(this);

        registerForContextMenu(getListView());

        getContentFromServer();
    }

    private AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
        @Override
        public void run(AccountManagerFuture<Bundle> future) {
            if (future.isCancelled()) {
                PersonalArtistAlbumActivity.this.finish();
            } else if (future.isDone()) {
                getContentFromServer();
            }
        }
    };

    private void getContentFromServer() {
        mListType = getIntent().getType();
        mTicket = AccountUtils.getUserData(this,
                AccountUtils.BORQS_ACCOUNT_OPTIONS_KEY_SESSION);
        if (mListType.equals(MusicUtils.TypeDefs.ONLINE_PERSONAL_ARTIST)) {
            GetPersonalArtistAlbumTask artistTask = new GetPersonalArtistAlbumTask(
                    new TaskAdapter() {
                        public void onFail(Task task) {
                            mHandler.sendEmptyMessage(MSG_TASK_FAILED);
                            MusicUtils.checkSessionExpired(task.getErrorReason().code,
                                    PersonalArtistAlbumActivity.this,
                                    callback);
                        }

                        @SuppressWarnings("unchecked")
                        public void onDone(Task task) {
                            mList = (List<SingerInfo>) task.getResult();
                            mHandler.sendEmptyMessage(MSG_CREATE_LIST);
                        }

                        public void onCancel(Task task) {
                        }
                    }, mTicket, 1);
            MusicExecutor.executeTask(artistTask);
            //setTitle(R.string.absent_local_list_title_artist);
            MusicUtils.initTitleBar(this, getListView(), getString(R.string.absent_local_list_title_artist));
        } else if (mListType.equals(MusicUtils.TypeDefs.ONLINE_PERSONAL_ALBUM)) {
            GetPersonalArtistAlbumTask albumTask = new GetPersonalArtistAlbumTask(
                    new TaskAdapter() {
                        public void onFail(Task task) {
                            mHandler.sendEmptyMessage(MSG_TASK_FAILED);
                            MusicUtils.checkSessionExpired(task.getErrorReason().code,
                                    PersonalArtistAlbumActivity.this,
                                    callback);
                        }

                        @SuppressWarnings("unchecked")
                        public void onDone(Task task) {
                            mList = (List<SingerInfo>) task.getResult();
                            mHandler.sendEmptyMessage(MSG_CREATE_LIST);
                        }

                        public void onCancel(Task task) {
                        }
                    }, mTicket, 2);
            MusicExecutor.executeTask(albumTask);
            //setTitle(R.string.absent_local_list_title_album);
            MusicUtils.initTitleBar(this, getListView(), getString(R.string.absent_local_list_title_album));
        }

        showDialog(DIALOG_LOADING_SONGS);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Intent intent = new Intent(this, PersonalMusicListActivity.class);
        String key = "";
        if (mListType.equals(MusicUtils.TypeDefs.ONLINE_PERSONAL_ARTIST)) {
            key = mList.get(position).name;
            intent.putExtra("artist", key);
            intent.setDataAndType(Uri.EMPTY, MusicUtils.TypeDefs.ONLINE_PERSONAL_ARTIST);
        } else if (mListType.equals(MusicUtils.TypeDefs.ONLINE_PERSONAL_ALBUM)) {
            key = mList.get(position).name;
            intent.putExtra("album", key);
            intent.setDataAndType(Uri.EMPTY, MusicUtils.TypeDefs.ONLINE_PERSONAL_ALBUM);
        }
        startActivity(intent);

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        AlertDialog dialog = null;
        switch (id) {
            case DIALOG_LOADING_SONGS:
                dialog = new ProgressDialog(this);
                dialog.setIcon(android.R.drawable.ic_dialog_info);
                dialog.setTitle(R.string.dialog_loading_songs_title);
                dialog.setMessage(getString(R.string.dialog_loading_songs_message));
                dialog.setCancelable(true);
                return dialog;
            default:
                break;
        }
        return super.onCreateDialog(id);
    }
}
